import NProgress from 'nprogress'
import { useUserStore } from "@/store/user"
import { ElMessage } from 'element-plus'
import { Router } from 'vue-router'

export default function routerGuard(router: Router) {
  router.beforeEach((to: any, from, next) => {
    const store = useUserStore()
    NProgress.start()

    console.log("from", from.name, " navi to ", to.name)
    console.log("token ", store.token)
    console.log("user ", store.userInfo)

    // 如果是访问登录页
    if (to.name === 'Signin') {
        if (store.token && store.userInfo) {
            next({ name: 'Index' })
        } else {
            next()
        }
        return
    }

    // 非登录页面
    if (!store.token) {
        next({ name: 'Signin' })
        return
    }

    // 有token但没有用户信息
    if (!store.userInfo) {
      store.getUserInfo().then(()=>{
        console.log("change to next page")
        next()
      }).catch(()=>{
        ElMessage.error('获取用户信息失败')
        store.singout()
        next({ name: 'Signin' })
      })
      return
    }
    
    next()
  })
  
  // 路由加载后
  router.afterEach((to, from) => {
    NProgress.done()
  })
}